package com.javaweb.controller;

import com.javaweb.controller.common.ResponseResult;
import com.javaweb.controller.common.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

/**
 * @desc:
 * @author: Ping
 * @date: 2024/10/30 9:51
 */
@RestController
@RequestMapping("/data")
@Slf4j
public class DataController {

    @GetMapping("/param/simple")
    // http://localhost:8080/chpt_04_springmvc
    // /data/param/simple?username=zhangsan&age=18
    // QueryString: username=zhangsan&age=18
    public String processSimpleData(
            @RequestParam(defaultValue = "zhangsan") String username,
            @RequestParam Integer age) {
        log.info("username: {}, age: {}", username, age);
        return "username: " + username + ", age:" + age;
    }

    @PostMapping("/param/object")
    public String processObjectData(@ModelAttribute UserDto userDto) {
        log.info("username: {}, password: {}", userDto.getUsername(), userDto.getPassword());
        return "username: " + userDto.getUsername() + ", password:" + userDto.getPassword();
    }
    // json request and json response

    // user {zhangsan, 123456}   -> formate   ->
    // serializable: object -->  string in certain format ?? (json)
    //  {
    //      "username":"zhangsan",
    //      "password":"123456",
    //       "age": 18,
    //       "roles":["admin", "teacher", "dean"]
    //       "father": {
    //               "name":"lisi",
                //   "other_key":"value"
    //       }
    //   }

    // deserializable:  json-string    --- > object
      //          json-str   --->  user

    @PostMapping("/resp/json")
    public ResponseResult<String> processJsonData(UserDto userDto) {

        if (! "123456".equals(userDto.getPassword())) {
            return ResponseResult.error(HttpStatus.BAD_REQUEST,
                    "请求参数出错!");
        }
        return ResponseResult.ok("验证成功");
    }

    @PostMapping("/full/json")
    public ResponseResult<String> processFullJson(
            @RequestBody UserDto userDto) {
        log.info("userDto: {}", userDto) ;
        if (! "123456".equals(userDto.getPassword())) {
            return ResponseResult.error(HttpStatus.BAD_REQUEST,
                    "请求参数出错!");
        }
        return ResponseResult.ok("验证成功");
    }


}
